using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace PS.WssSync.Utils
{
    public class XmlSerializationHelper<Class>
    {
        private readonly XmlSerializer serializer;
        
        public XmlSerializationHelper()
            : this(null)
        {
        }

        public XmlSerializationHelper(Action<XmlAttributeOverrides> addOverrides)
        {
            XmlAttributeOverrides overrides = new XmlAttributeOverrides();
            if (null != addOverrides)
            {
                addOverrides(overrides);
            }
            serializer = new XmlSerializer(typeof(Class), overrides);
        }

        public  Class DeserializeFromFile(string filePath)
        {
            using (FileStream stream = new FileStream(filePath, FileMode.Open))
            {
                return (Class)serializer.Deserialize(stream);
            }
        }

        public  void SerializeToFile(Class data, string filePath)
        {
            using (FileStream stream = new FileStream(filePath, FileMode.Create))
            {
                serializer.Serialize(stream, data);
            }
        }

        public Class Deserialize(string xmlString)
        {
            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
            {
                return (Class)serializer.Deserialize(stream);
            }
        }

        public string Serialize(Class data)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, data);
                stream.Position = 0;
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                return Encoding.UTF8.GetString(bytes);
            }
        }
    }
}